package cn.tedu.jsd2207csmallpassport.config;

import cn.tedu.jsd2207csmallpassport.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    public SecurityConfiguration(){
        log.info("创建配置类对象: Security");
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
       //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //如果不调用父类方法,默认所有请求都不需要通过认证,可以直接访问
        /*super.configure(http);*/

        //白名单  无需登录,即可访问
        String[] urls ={
                "/favicon.ico",
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/admins/login"
        };
        // 启用CorsFilter (Spring Security)
        http.cors();

        //将防止伪造的跨域攻击的机制禁用
        http.csrf().disable();

        //提示 关于请求路径的配置,如果同一路径对应多项配置规则,以第一次配置的为准
        http.authorizeRequests()//管理请求授权

                    /*.mvcMatchers(HttpMethod.OPTIONS,"/**")
                    .permitAll()*/

                    .mvcMatchers(urls) //匹配某些路径
                    .permitAll() //直接许可. 即可访问认证即可访问
                    .anyRequest()//除了以上配置过的以外的其它所有请求
                    .authenticated(); // 要求是" 已经通过认证的"

        //
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);

        //启用登录表单
        //当未认证时
        // -- 如果启用了表单,会自动重定向到登录表单
        // --如果未启用表单,会提示403错误
        //http.formLogin();

    }
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;
}
